package com.cnunicom.modules.mp.handle;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.cnunicom.common.utils.DateUtils;
import com.cnunicom.modules.mp.builder.TextBuilder;
import com.cnunicom.modules.mp.entity.WxMpUserEntity;
import com.cnunicom.modules.mp.service.WxMpUserService;
import org.springframework.stereotype.Component;

import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

import javax.annotation.Resource;

/**
 * @author dingziyuan
 */
@Component
public class SubscribeHandler extends AbstractHandler {

    @Resource
    private WxMpUserService wxMpUserService;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService weixinService,
                                    WxSessionManager sessionManager) throws WxErrorException {

        this.logger.info("新关注用户 OPENID: " + wxMessage.getFromUser());

        // 获取微信用户基本信息
        try {
            WxMpUser userWxInfo = weixinService.getUserService()
                .userInfo(wxMessage.getFromUser(), null);
            if (userWxInfo != null) {
                // TODO 可以添加关注用户到本地数据库
                saveToLocal(userWxInfo);
            }
        } catch (WxErrorException e) {
            if (e.getError().getErrorCode() == 48001) {
                this.logger.info("该公众号没有获取用户信息权限！");
            }
        }


        WxMpXmlOutMessage responseResult = null;
        try {
            responseResult = this.handleSpecial(wxMessage);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
        }

        if (responseResult != null) {
            return responseResult;
        }

        try {
            return new TextBuilder().build("感谢您关注运城宾馆", wxMessage, weixinService);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
        }

        return null;
    }

    /**
     * 处理特殊请求，比如如果是扫码进来的，可以做相应处理
     */
    private WxMpXmlOutMessage handleSpecial(WxMpXmlMessage wxMessage)
        throws Exception {
        //TODO
        return null;
    }

    /**
     * 保存到本地数据库
     * @param userWxInfo
     */
    private void saveToLocal(WxMpUser userWxInfo) {

        final WxMpUserEntity entity = new WxMpUserEntity();
        entity.setSubscribe(userWxInfo.getSubscribe());
        entity.setOpenId(userWxInfo.getOpenId());
        entity.setNickname(userWxInfo.getNickname());
        entity.setSexDesc(userWxInfo.getSexDesc());
        entity.setSex(userWxInfo.getSex());
        entity.setLanguage(userWxInfo.getLanguage());
        entity.setCity(userWxInfo.getCity());
        entity.setProvince(userWxInfo.getProvince());
        entity.setCountry(userWxInfo.getCountry());
        entity.setCountry(userWxInfo.getCountry());
        entity.setCity(userWxInfo.getCity());
        entity.setHeadImgUrl(userWxInfo.getHeadImgUrl());
        entity.setSubscribeTime(LocalDateTime
                .ofInstant(Instant.ofEpochMilli(userWxInfo.getSubscribeTime() * 1000L), ZoneId.systemDefault())
                .format(DateTimeFormatter.ofPattern(DateUtils.DATE_TIME_PATTERN)));
        entity.setUnionId(userWxInfo.getUnionId());
        entity.setRemark(userWxInfo.getRemark());
        entity.setGroupId(userWxInfo.getGroupId());
        entity.setTagIds(Arrays.toString(userWxInfo.getTagIds()));
        entity.setPrivileges(Arrays.toString(userWxInfo.getPrivileges()));
        entity.setSubscribeScene(userWxInfo.getSubscribeScene());
        entity.setQrScene(userWxInfo.getQrScene());
        entity.setQrSceneStr(userWxInfo.getQrSceneStr());

        final UpdateWrapper<WxMpUserEntity> wrapper = new UpdateWrapper<>();
        wrapper.eq("open_id", entity.getOpenId());

        wxMpUserService.saveOrUpdate(entity, wrapper);
    }
}
